package com.rjpacket.supernews.app.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.util.LruCache;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Created by aaa on 15-3-11.
 */

/**
 * 图片内存缓存
 */
public class ImageCache {
    private static ImageCache ourInstance = null;

    public static ImageCache getInstance() {
        if (ourInstance == null) {
            ourInstance = new ImageCache();
        }
        return ourInstance;
    }

    //一级缓存
    private LruCache<String, Bitmap> firstCache;
    //二级缓存
    private HashMap<String, SoftReference<Bitmap>> secondCache;

    /**
     * 初始化图片一级缓存
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    private ImageCache() {
        long freeMemory = Runtime.getRuntime().freeMemory();
        if (freeMemory > 0) {
            freeMemory = freeMemory / 8;
        } else {
            freeMemory = 5 * 1024 * 1024;
        }

        firstCache = new LruCache<String, Bitmap>((int) freeMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                int size = 0;

                if (Build.VERSION.SDK_INT >= 19) {
                    size = value.getAllocationByteCount();
                } else {
                    int rowBytes = value.getRowBytes();
                    int height = value.getHeight();
                    size = rowBytes * height;
                }

                return size;
            }
        };

        //初始化图片二级缓存
        secondCache = new LinkedHashMap<String, SoftReference<Bitmap>>();
    }

    /**
     * 根据图片的url获取到缓存里的图片
     *
     * @param url
     * @return
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    public Bitmap getImage(String url) {
        Bitmap ret = null;
        if (url != null) {
            ret = firstCache.get(url);
            if (ret == null) {
                if (secondCache.containsKey(url)) {
                    SoftReference<Bitmap> reference = secondCache.get(url);
                    if (reference != null) {
                        ret = reference.get();
                    }
                }
            }
        }
        return ret;
    }

    /**
     * 将图片以网址与图片数据的键值对的关系存入图片缓存
     *
     * @param url
     * @param bitmap
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    public void putImage(String url, Bitmap bitmap) {
        if (url != null && bitmap != null) {
            secondCache.put(url, new SoftReference<Bitmap>(bitmap));

            firstCache.put(url, bitmap);
        }
    }
}
